import {Component, Output, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {HttpServicesProvider} from "../../providers/http-services/http-services";
import {ValidateProvider} from "../../providers/validate/validate";
import {UrlProvider} from "../../providers/url/url";
import {UtilsProvider} from "../../providers/utils/utils";
import {WechatProvider} from "../../providers/wechat/wechat";
import {ConfigProvider} from "../../providers/config/config";
import {CommonProvider} from "../../providers/common/common";
import {StorageProvider} from "../../providers/storage/storage";

@IonicPage({
    segment:'article/detail/:id',
    defaultHistory:['ServiceAgencyPage']
})
@Component({
    selector: 'page-article-detail',
    templateUrl: 'article-detail.html',
})
export class ArticleDetailPage {
    @ViewChild('share') share;
    @Output('reply') reply;
    params = {
        amoyId : 0
    };
    infoData = {};
    collected:boolean = false;
    liked:boolean = false;
    type_id  = 1;
    msgData = {
        message : '',
        amoy_id : 0,
        token   : '',
        type    : 1,
        content : ''
    };
    comments = {};
    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        public httpService:HttpServicesProvider,
        public validate: ValidateProvider,
        public url: UrlProvider,
        public storage: StorageProvider,
        public util: UtilsProvider,
        public wechat: WechatProvider,
        public config: ConfigProvider,
        public common: CommonProvider
    ) {
    }
    ionViewCanEnter(){
        return this.validate.checkLogin();
    }
    ionViewWillEnter(){
        this.params.amoyId = this.navParams.get('id');
        this.type_id =  this.navParams.get('type_id');
        this.getData();
    }

    ionViewDidEnter(){
        this.wechat.getWxConfig(()=>{
            // this.wechat.wxShareMoments({shareNumber:3, shareTitle:this.infoData['title'], amoyId: this.params.amoyId});
            // this.wechat.wxShareFriend({shareNumber:3, shareTitle:this.infoData['title'], amoyId: this.params.amoyId});
            this.shareResult();
        });
    }

    /**
     * 页面加载获取数据
     * */
    getData() {
        let apiUrl = "/service/get_info_detail";
        this.httpService.requestPostData(apiUrl, {
            amoy_id: this.params.amoyId,
            token: this.config.getToken()
        },response => {
            this.infoData = response['data'];
            //替换Mp3文件
            this.infoData['auto_content'] = this.infoData['auto_content'].replace(/<(embed).*src="(.*\.(mp3))"[^>]*>/gi, '<video src="$2" controls="controls" height="50" width="100%"></video>');
            //替换Mp4文件
            this.infoData['auto_content'] = this.infoData['auto_content'].replace(/<(embed).*src="(.*\.(mp4))"[^>]*>/gi, '<video src="$2" controls="controls" height="250" width="100%"></video>');
            //修改收藏状态
            this.collected = this.infoData['has_collect'];
            this.liked = this.infoData['zan_collect'];

            //留言列表
            this.comments = response['data']['comment'];


        });
    }

    /**
     * 文章收藏
     * */
    collect(amoy_id){
        if(this.collected == true){
            this.util.presentAlert('官人，这篇美文已经收藏过啦！');
            return false;
        }
        this.common.collect(amoy_id,(response)=>{
            if(response.code == 200){
                if(response['message'] == '收藏成功'){
                    this.collected = true;
                    this.util.presentAlert('收藏成功');
                }else{
                    this.collected = false;
                    this.util.presentAlert('文章已取消收藏');
                }
            }else{
                this.util.presentAlert('系统有误，请稍后再试！')
            }
        });
    }

    /**
     * 文章点赞
     * */
    like(amoy_id){
        this.common.like(amoy_id,(response)=>{
            if(response.code == 200){
                this.infoData['zan_num'] = response['data']['zan_num'];
                this.liked = response['message'] == '点赞成功';
            }else{
                this.util.presentAlert('系统有误，请稍后再试！')
            }
        });
    }

    /**
     * 发送留言
     * */
    sendMsg(reply_uid=0){
        this.msgData['amoy_id'] = this.params.amoyId;
        this.msgData['token'] = this.config.getToken();
        this.msgData['p_id'] = reply_uid ? reply_uid : 0;
        let apiUrl = "/comment/add_comment_handle";
        this.httpService.requestPostData(apiUrl,this.msgData,(response)=>{
            this.msgData = {
                message : '',
                amoy_id : 0,
                token   : '',
                type    : 1,
                content : ''
            };
            this.sendMsgSuccess();
        })
    }

    /**
     * 留言成功后获取数据
     * */
    sendMsgSuccess(){
        let apiUrl = "/comment/get_comment_list";
        this.httpService.requestPostData(apiUrl,{
            token: this.config.getToken(),
            amoy_id: this.params.amoyId
        },(response)=>{
            this.comments = response['data'];
        })
    }

    /**
     * 分享结果
     * */
    shareResult(title=''){
        if(title == '' || title == undefined){
            title = this.infoData['title'];
        }
        let userInfo = JSON.parse(this.storage.get('userInfo'));
        //分享到朋友圈
        this.wechat.wxShareMoments({shareNumber: 3, amoyId: this.params.amoyId, shareTitle: title, userId:userInfo.user_id}, ()=>{
            // let apiUrl = "/task_info/insert_share";
            // this.httpService.requestPostData(apiUrl, {
            //     token:this.config.getToken(),
            //     amoy_id: this.params.amoyId
            // },() => {
            //     this.getData();
            // });
        });

        //分享到朋友
        this.wechat.wxShareFriend({shareNumber: 3, amoyId: this.params.amoyId, shareTitle: title, userId:userInfo.user_id}, ()=>{
            // let apiUrl = "/task_info/insert_share";
            // this.httpService.requestPostData(apiUrl, {
            //     token:this.config.getToken(),
            //     amoy_id: this.params.amoyId
            // },() => {
            //     this.getData();
            // });
        });
    }
}
